package com.centriole.service.workflow.common;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @功能: 字符串工具类
 * @作者:chanson
 * @时间:2018/5/23 21:11
 */
public class StringConventor {

    /**
     * 转义正则特殊字符 （$()*+.[]?\^{},|）
     * @param keyword
     * @return
     */
    public static String escapeExprSpecialWord(String keyword) {
        if (keyword!=null) {
            String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword;
    }

    /**
     * 对含有特定占位符的字符串进行替换
     * @param orignal       原始字符串
     * @param prefix        占位符前缀
     * @param suffix        占位符后缀
     * @param paramsMap     参数列表map
     * @return
     */
    public static String placeHolder(String orignal ,String prefix , String suffix , Map<String,String> paramsMap){
        Map<String,String> resStringMap = new HashMap<>();
        if(paramsMap == null || paramsMap.size() == 0) return orignal;
        try {
            resStringMap = Stream.of(orignal.split(escapeExprSpecialWord(prefix)))
                    .parallel()
                    .filter(e -> e.contains(suffix))
                    .map(e -> e.split(escapeExprSpecialWord(suffix))[0])
                    .collect(Collectors.toMap(k -> prefix + k + suffix, v -> paramsMap.get(v) ));
        }catch (NullPointerException e){
            System.out.println("找不到参数");
        }
        for( Map.Entry<String,String> entry : resStringMap.entrySet() ){
            orignal = orignal.replace(entry.getKey() , entry.getValue());
        }
        return orignal;
    }

    public static void main(String[] args) {
        String url = "localhost:13000/foo?processId=${processId}&type=${type}&isFile=${isFile}";
        Map<String,String> hashMap = new HashMap<>();
        hashMap.put("processId","123456");
        hashMap.put("type","admin");
        hashMap.put("isFile","1");
        String s = placeHolder(url, "${", "}", hashMap);
        System.out.println(s);
    }


}

